package com.yazi.mxz.common.service.impl;


import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;

import com.myframework.smhj.common.tool.CommonUtil;
import com.myframework.smhj.common.tool.DateUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yazi.mxz.common.ComSetting;
import com.yazi.mxz.common.db.dao.MemberDao;
import com.yazi.mxz.common.db.dao.PrizeDao;
import com.yazi.mxz.common.db.dao.PrizeWinDao;
import com.yazi.mxz.common.entity.ValueFactory;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.beans.Prize;
import com.yazi.mxz.common.entity.beans.PrizeWin;
import com.yazi.mxz.common.entity.enums.PrizeStatus;
import com.yazi.mxz.common.entity.enums.PrizeType;
import com.yazi.mxz.common.entity.enums.PrizeWinStatus;
import com.yazi.mxz.common.entity.enums.SettingId;
import com.yazi.mxz.common.service.ShakeService;

@Service("shakeService")
public class ShakeServiceImpl implements ShakeService {
	private static Logger log = LoggerFactory.getLogger(ShakeServiceImpl.class);
	
	@Resource
	PrizeDao prizeDao;
	@Resource
	PrizeWinDao prizeWinDao;
	@Resource
	MemberDao memberDao;
	
	@Override
	public PrizeWin shake(Member member) {
		log.debug("shake：memberId={}", member.getMemberId());
		
		if (member.getShakeCount() <= 0) {
			log.debug("shake：memberId={},抽奖次数已用完", member.getMemberId());
			return null;
		}
		
		// 减抽奖次数
		member.setShakeCount(member.getShakeCount() - 1);
		member.setShakeTime(DateUtil.getTimeStamp());
		memberDao.merge(member);
		
		// 获取奖品列表
		Prize prize4s = new Prize();// prize for search
		prize4s.setStatus(PrizeStatus.SOLD_IN.ordinal());
		List<Prize> prizeList = prizeDao.listByExample(prize4s);
		int prizeSize = prizeList.size();
		// 没有可用奖品,则不会中奖
		if (prizeSize == 0) {
			log.debug("shake：奖品已用完");
			return null;
		}
		
		// 中奖概率
		double winRate = Double.parseDouble(ComSetting.getSetting(SettingId.SHAKE_WIN_RATE).getValue());
		
		// 未中奖
		if (Math.random() > winRate) {
			log.debug("shake：memberId={},未抽中", member.getMemberId());
			return null;
		}
		
		// 抽中的奖品
		Prize winPrize = null;
		double rate = Math.random();
		double prizeRate = 0;
		for (Prize prize : prizeList) {
			prizeRate += prize.getRate();
			if (rate < prizeRate) {
				winPrize = prize;
				log.debug("shake：memberId={},抽中‘{}’", winPrize.getName(), member.getMemberId());
				break;
			}
		}
		
		// 各奖品概率总和不等于100%时的问题
		if (null == winPrize) {
			return null;
		}
		
		PrizeWin prizeWin = new PrizeWin();
		ValueFactory.validate(prizeWin);
		prizeWin.setAddTime(DateUtil.getTimeStamp());
		prizeWin.setConvertCode(CommonUtil.randomLN(6));
		prizeWin.setExpiredTime(0L);// 永不过期
		if (winPrize.getExpiredDay() > 0) {
			// 有效期(天),按整天,以中奖当天0时作为开始时间来计算有效期
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			cal.add(Calendar.DATE, winPrize.getExpiredDay());
			prizeWin.setExpiredTime(cal.getTimeInMillis());
		}
		prizeWin.setMember(member);
		prizeWin.setName(winPrize.getName());
		prizeWin.setStatus(PrizeWinStatus.NORMAL.ordinal());
		prizeWin.setSummary(winPrize.getSummary());
		prizeWin.setType(winPrize.getType());
		prizeWin.setWorth(winPrize.getWorth());
		prizeWin.setWinId(null);
		
		// 直接入账
		switch (PrizeType.values()[winPrize.getType()]) {
		case INTEGRAL :// 积分
			member.setIntegral(member.getIntegral() + winPrize.getWorth().intValue());
			prizeWin.setStatus(PrizeWinStatus.CONVERTED.ordinal());
			prizeWin.setUseTime(DateUtil.getTimeStamp());
			break;
		case SHAKE_COUNT :// 摇奖次数
			member.setShakeCount(member.getShakeCount() + winPrize.getWorth().intValue());
			prizeWin.setStatus(PrizeWinStatus.CONVERTED.ordinal());
			prizeWin.setUseTime(DateUtil.getTimeStamp());
			break;
		default:
			break;
		}
		
		prizeWinDao.persist(prizeWin);
		memberDao.merge(member);
		
		// 奖品数量减1
		winPrize.setAmount(winPrize.getAmount() - 1);
		// 如果没有奖品了则直接下线
		if (winPrize.getAmount() <= 0) {
			winPrize.setStatus(PrizeStatus.SOLD_OUT.ordinal());
		}
		prizeDao.merge(winPrize);
		
		return prizeWin;
	}

	@Override
	public int shakeCount(Member member) {
		log.debug("shakeCount：memberId={}", member.getMemberId());
		// 当前时间
		Calendar cal = Calendar.getInstance();
		int curMonth = cal.get(Calendar.MONTH);
		int curDate = cal.get(Calendar.DATE);
		
		// 上次摇奖时间
		cal.setTimeInMillis(member.getShakeTime());
		int shakeMonth = cal.get(Calendar.MONTH);
		int shakeDate = cal.get(Calendar.DATE);
		
		// 不是同一个月或者不是同一天,将摇奖次数重置
		if (curMonth != shakeMonth || curDate != shakeDate) {
			int shakeCount = Integer.parseInt(ComSetting.getSetting(SettingId.SHAKE_COUNT).getValue());
			member.setShakeCount(shakeCount);
			memberDao.merge(member);
		}
		
		return member.getShakeCount();
	}

}
